package com.qqs.socket;

import java.util.List;

import org.apache.log4j.Logger;

import com.qqs.business.media.PlayMusic;
import com.qqs.util.ConvertUtil;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class ByteToDecoder extends ByteToMessageDecoder {

	private static final Logger logger = Logger.getLogger(TcpServer.class);

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		// TODO Auto-generated method stub
		if (in.readableBytes() < 3 || in.readableBytes() > 100)
			return;
		ChannelManager.SetChannelActiveMap(ctx);
		byte[] headerbuffer = new byte[3];
		in.readBytes(headerbuffer);
		if ((headerbuffer[0] & 0xFF) == 0x55 && (headerbuffer[1] & 0xFF) == 0x00) {
			int nlenth = (headerbuffer[2] & 0xFF) + 11;
			byte[] databuffer = new byte[nlenth];
			in.readBytes(databuffer);
			byte[] data = new byte[3 + nlenth];
			System.arraycopy(headerbuffer, 0, data, 0, 3);
			System.arraycopy(databuffer, 0, data, 3, nlenth);
			String datastr = ConvertUtil.Byte2HexString(data, data.length);
			logger.debug(datastr);
			ProtocolAnalysis.dealEnocean(data);// 接受数据的处理方法
		} else if ((headerbuffer[0] & 0xFF) == 0xAA && (headerbuffer[1] & 0xFF) == 0x55) {// wifi
			int nlenth = (headerbuffer[2] & 0xFF);
			byte[] databuffer = new byte[nlenth];
			in.readBytes(databuffer);
			byte[] data = new byte[3 + nlenth];
			System.arraycopy(headerbuffer, 0, data, 0, 3);
			System.arraycopy(databuffer, 0, data, 3, nlenth);
			String datastr = ConvertUtil.Byte2HexString(data, data.length);
			logger.debug(datastr);
			ProtocolAnalysis.dealWifi(data);// 接受数据的处理方法
		}
	}

}
